package com.zxb.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理程序
 * Order(-1)：优先级一定要比ResponseStatusExceptionHandler低
 *
 * @author zhuxiongbin
 * @date 2023/03/27
 */
@Component
@Order(-1)
@Slf4j
public class GlobalErrorExceptionHandler implements ErrorWebExceptionHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable throwable) {

        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(throwable);
        }

        //返回json格式 , 可以根据业务输出
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (throwable instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) throwable).getStatus());
        }else{
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        DataBuffer buffer = null;
        try {
            //todo 返回响应结果，根据业务需求，自己定制
            Map<String,Object> resultMsg = new HashMap<>(2);
            resultMsg.put("code",HttpStatus.INTERNAL_SERVER_ERROR.value());
            resultMsg.put("message",throwable.getMessage());
            byte[] bytes = objectMapper.writeValueAsBytes(resultMsg);
            buffer = response.bufferFactory().wrap(bytes);
        } catch (JsonProcessingException e) {
            log.error("Error writing response", throwable);
            buffer = response.bufferFactory().wrap(new byte[0]);
        }

        return response.writeWith(Mono.just(buffer));
    }
}
